package io.renren.modules.sys.controller;

import java.io.IOException;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.DateUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.TiananCheckEntity;
import io.renren.modules.sys.entity.TiananFuyiEntity;
import io.renren.modules.sys.entity.TiananSubmitEntity;
import io.renren.modules.sys.service.*;
import io.renren.modules.sys.service.impl.TiananServiceImpl;
import io.renren.modules.sys.util.DateUtil;
import io.renren.modules.sys.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.sys.entity.TiananEntity;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 提案
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2021-03-14 21:48:35
 */
@RestController
@RequestMapping("sys/tianan")
public class TiananController extends AbstractController {
    @Autowired
    private TiananService tiananService;
    @Autowired
    private TiananFuyiService tiananFuyiService;

    @Autowired
    private TiananSubmitService tiananSubmitService;
    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private SysYearService sysYearService;

    /**
     * 列表公示
     */
    @RequestMapping("/start")
    public R start() {


        String endtime = sysConfigService.getValue("endtime");
        String start = "";
        try {
            Date date = DateUtil.formatString(endtime, "yyyy-MM-dd");
            Date date1 = new Date();
            start = "" + date1.compareTo(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("endtime", endtime).put("start", start);
    }

    /**
     * 列表公示
     */
    @RequestMapping("/listyear")
    public R listyear() {


        return R.ok().put("year", tiananService.listyear());
    }

    /**
     * 列表公示
     */
    @RequestMapping("/listjilu")
    public R listjilu(@RequestParam Map<String, Object> params) {
        PageUtils page = tiananService.queryPagejilu(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表公示
     */
    @RequestMapping("/listgongshi")
    public R listgongshi(@RequestParam Map<String, Object> params) {
        PageUtils page = tiananService.queryPagegongshi(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表公示
     */
    @RequestMapping("/listgongshichuli")
    public R listgongshichuli(@RequestParam Map<String, Object> params) {
        PageUtils page = tiananService.queryPagegongshichuli(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表qianpi
     */
    @RequestMapping("/listqianpi")
    public R listqianpi(@RequestParam Map<String, Object> params) {
        PageUtils page = tiananService.queryPageqianpi(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:tianan:list")
    public R list(@RequestParam Map<String, Object> params) {

        PageUtils page = tiananService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 列表
     */
    @RequestMapping("/exports")
    public void list(HttpServletRequest request, HttpServletResponse response) {

        List<TiananEntity> list = tiananService.lists();
        String[] headers = {"序号", "提案标题", "类型", "案由分析", "措施建议", "提案人", "部门"};
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        //设置列宽
        sheet.setDefaultColumnWidth((short) 18);
        //创建第一行的对象，第一行一般用于填充标题内容。从第二行开始一般是数据
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            //创建单元格，每行多少数据就创建多少个单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            //给单元格设置内容
            cell.setCellValue(text);
        }

        //遍历集合，将每个集合元素对象的每个值填充到单元格中
        for (int i = 0; i < list.size(); i++) {
            TiananEntity entity = list.get(i);
            //从第二行开始填充数据
            row = sheet.createRow(i + 1);
            //该集合只记录数量和时间，这两个值来自statisticsModel。如果对象比较复杂，需要额外转换，比如Date类型的日期，int，float类型的数值
            List<String> datas = new ArrayList<>();

            datas.add("" + (i + 1));
            datas.add(entity.getTitle());
            datas.add(entity.getTypesName());
            datas.add(entity.getAnyoufenxi());
            datas.add(entity.getCuoshijianyi());
            datas.add(entity.getCreatusername());
            datas.add(entity.getDeptIdName());
            for (int j = 0; j < datas.size(); j++) {
                String string = datas.get(j);
                HSSFCell cell = row.createCell(j);
                HSSFRichTextString richString = new HSSFRichTextString(string);
                HSSFFont font3 = workbook.createFont();
                //定义Excel数据颜色，这里设置为蓝色
                richString.applyFont(font3);
                cell.setCellValue(richString);
            }

        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + "Devices.xls");//Excel文件名
        try {
            response.flushBuffer();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //将workbook中的内容写入输出流中
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 列表附议
     */
    @RequestMapping("/listfuyi")
    public R listfuyi(@RequestParam Map<String, Object> params) {
        params.put("userId", getUserId());
        PageUtils page = tiananService.queryPagefuyi(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表附议
     */
    @RequestMapping("/listlianming")
    public R listlianming(@RequestParam Map<String, Object> params) {
        params.put("userId", getUserId());
        PageUtils page = tiananService.queryPagelianming(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表预审
     */
    @RequestMapping("/listyushen")
    @RequiresPermissions("sys:tianan:yushen")
    public R listyushen(@RequestParam Map<String, Object> params) {
        PageUtils page = tiananService.queryPageyushen(params);

        return R.ok().put("page", page);
    }

    /**
     * 立案
     */
    @RequestMapping("/listlian")
    @RequiresPermissions("sys:tianan:lian")
    public R listlian(@RequestParam Map<String, Object> params) {
        PageUtils page = tiananService.queryPagelian(params);

        return R.ok().put("page", page);
    }

    /**
     * lian
     */
    @RequestMapping("/listlians")
    public R listlians(@RequestParam Map<String, Object> params) {
        PageUtils page = tiananService.queryPagelian(params);

        return R.ok().put("page", page);
    }

    /**
     * 选区
     */
    @RequestMapping("/listxuanqu")
    public R listxuanqu(@RequestParam Map<String, Object> params) {
        PageUtils page = tiananService.queryPagexuanqu(params);

        return R.ok().put("page", page);
    }

    /**
     * 处理
     */
    @RequestMapping("/listchuli")
    public R listchuli(@RequestParam Map<String, Object> params) {
        PageUtils page = tiananService.queryPagechuli(params);

        return R.ok().put("page", page);
    }


    /**
     * 处理
     */
    @RequestMapping("/listchulis")
    public R listchulis(@RequestParam Map<String, Object> params) {
        PageUtils page = tiananService.queryPagechulis(params);

        return R.ok().put("page", page);
    }

    /**
     * banli
     */
    @RequestMapping("/listbanli")
    public R listbanli(@RequestParam Map<String, Object> params) {
        PageUtils page = tiananService.queryPagebanli(params);

        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") String id) {
        TiananEntity tianan = tiananService.getid(id);


        return R.ok().put("tianan", tianan);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:tianan:save")
    public R save(@RequestBody TiananEntity tianan) {
        tianan.setCreateTime(new Date());
        tianan.setUpdateTime(new Date());
        if (tianan.getDeptId() == null) {
            tianan.setDeptId(getDeptId());
        }
        tianan.setCreatuser("" + getUserId());
        tianan.setXuanqu(getUser().getXuanqu());
        tianan.setCreateTime(new Date());
        String year = null;
        try {
            year = sysYearService.selectstart().getYear();

        } catch (Exception e) {
            e.getMessage();
        }
        if (StringUtil.isNotEmpty(year)) {
            tianan.setYear(year);
        } else {
            tianan.setYear(DateUtil.getCurrentYear());
        }
        tiananService.save(tianan);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:tianan:update")
    public R update(@RequestBody TiananEntity tianan) {
        ValidatorUtils.validateEntity(tianan);
        tianan.setUpdateTime(new Date());
        if (StringUtil.isEmpty(tianan.getLianmingstatus())) {
            tianan.setLianmingstatus("0");
        }
        if (StringUtil.isEmpty(tianan.getLianmingstatus())) {
            tianan.setFuyistatus("0");
        }
        tianan.setFuyistatus("0");
        tianan.setDelFlag(0);
        tiananService.updateById(tianan);
        TiananFuyiEntity tiananFuyiEntity = new TiananFuyiEntity();
        tiananFuyiEntity.setStatus("0");
        tiananFuyiService.update(tiananFuyiEntity, new QueryWrapper<TiananFuyiEntity>().eq("tianid", tianan.getId()));

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/chexiao")
    @RequiresPermissions("sys:tianan:update")
    public R chexiao(@RequestBody TiananEntity tianan) {
        ValidatorUtils.validateEntity(tianan);
        tianan.setUpdateTime(new Date());
        tiananService.updateById(tianan);
        return R.ok();
    }

    /**
     * 审批
     */
    @RequestMapping("/listshenpi")
    public R listshenpi(@RequestParam Map<String, Object> params) {
        PageUtils page = tiananService.queryPageshenpi(params);

        return R.ok().put("page", page);
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:tianan:delete")
    public R delete(@RequestBody Integer[] ids) {
        tiananService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/gongshi")
    public R gongshi(@RequestBody String[] ids) {

        List<String> resultList = new ArrayList<String>(Arrays.asList(ids));
        TiananEntity tianan = new TiananEntity();
        tianan.setGongshi("1");
        tiananService.update(tianan, new QueryWrapper<TiananEntity>().in("id", resultList));

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/nogongshi")
    public R nogpngshi(@RequestBody String[] ids) {

        List<String> resultList = new ArrayList<String>(Arrays.asList(ids));
        TiananEntity tianan = new TiananEntity();
        tianan.setGongshi("0");
        tiananService.update(tianan, new QueryWrapper<TiananEntity>().in("id", resultList));

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/updateyushen")
    public R updateyushen(@RequestBody TiananEntity tianan) {
        ValidatorUtils.validateEntity(tianan);
        tianan.setUpdateTime(new Date());
        tiananService.updateById(tianan);
        return R.ok();
    }

    /**
     * tijiao
     */
    @RequestMapping("/updatesubmit")
    public R updatesubmit(@RequestBody TiananEntity tianan) {
        ValidatorUtils.validateEntity(tianan);
        tianan.setUpdateTime(new Date());
        TiananSubmitEntity tiananSubmitEntity = new TiananSubmitEntity();
        tiananSubmitEntity.setCreateTime(new Date());
        tiananSubmitEntity.setSubexplain(tianan.getSubexplain());
        tiananSubmitEntity.setTianid("" + tianan.getId());
        tiananSubmitEntity.setSubfile(tianan.getSubfile());
        tiananSubmitEntity.setJingbanuser("" + getUserId());
        tiananService.updateById(tianan);
        tiananSubmitService.save(tiananSubmitEntity);
        return R.ok();
    }

    /**
     * 审核
     */
    @RequestMapping("/updatecheck")
    public R updatecheck(@RequestBody TiananEntity tianan) {
        ValidatorUtils.validateEntity(tianan);
        tianan.setUpdateTime(new Date());
        tianan.setRestime(new Date());
        tiananService.updateById(tianan);
        TiananSubmitEntity tiananSubmitEntity = new TiananSubmitEntity();
        tiananSubmitEntity.setId(Integer.parseInt(tianan.getSubmitid()));
        tiananSubmitEntity.setRescauseuser("" + getUserId());
        tiananSubmitEntity.setRescause(tianan.getRescause());
        tiananSubmitEntity.setRestime(new Date());
        tiananSubmitEntity.setBanjiestatus(tianan.getBanjiestatus());
        tiananSubmitService.updateById(tiananSubmitEntity);
        return R.ok();
    }

    /**
     * 审核
     */
    @RequestMapping("/updateshenpi")
    public R updateshenpi(@RequestBody TiananEntity tianan) {
        ValidatorUtils.validateEntity(tianan);
        tianan.setUpdateTime(new Date());
        tianan.setLedtime(new Date());
        tiananService.updateById(tianan);
        TiananSubmitEntity tiananSubmitEntity = new TiananSubmitEntity();
        tiananSubmitEntity.setId(Integer.parseInt(tianan.getSubmitid()));
        tiananSubmitEntity.setLeacauseuser("" + getUserId());
        tiananSubmitEntity.setLeacause(tianan.getLeacause());
        tiananSubmitEntity.setLedtime(new Date());
        tiananSubmitEntity.setBanjiestatus(tianan.getBanjiestatus());
        tiananSubmitService.updateById(tiananSubmitEntity);
        return R.ok();
    }

    /**
     * 办结
     */
    @RequestMapping("/fenxiover/{year}" )
    public R fenxiover(@PathVariable("year") String year) {
        return R.ok().put("data", tiananService.over(year));
    }

    /**
     * 超时
     */
    @RequestMapping("/fenxiovertime/{year}")
    public R fenxiovertime(@PathVariable("year") String year) {
        return R.ok().put("data", tiananService.overtime(year));
    }

    /**
     * manyi
     */
    @RequestMapping("/fenximanyi/{year}")
    public R fenximanyi(@PathVariable("year") String year) {
        return R.ok().put("data", tiananService.manyi(year));
    }

    /**
     * type
     */
    @RequestMapping("/fenxitype/{year}")
    public R updatetype(@PathVariable("year") String year) {
        return R.ok().put("data", tiananService.type(year));
    }

    /**
     * types
     */
    @RequestMapping("/fenxitypes/{year}")
    public R updatetypes(@PathVariable("year") String year) {
        return R.ok().put("data", tiananService.types(year));
    }

    /**
     * liantype
     */
    @RequestMapping("/fenxiliantype/{year}")
    public R updateliantype(@PathVariable("year") String year) {
        return R.ok().put("data", tiananService.liantype(year));
    }

    /**
     * liandept
     */
    @RequestMapping("/fenxiliandept/{year}")
    public R updateliandept(@PathVariable("year") String year) {
        return R.ok().put("data", tiananService.liandept(year));
    }

    /**
     * lianren
     */
    @RequestMapping("/fenxilianren/{year}")
    public R updatelianren(@PathVariable("year") String year) {
        return R.ok().put("data", tiananService.lianren(year));
    }
}
